/*
This file is part of AI Agent Feed.

"AI Agent Feed" is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

"AI Agent Feed" is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with "AI Agent Feed".  If not, see <http://www.gnu.org/licenses/>.
 */
package com.feed.protocol.http.impl;

import java.io.IOException;
import java.net.URI;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.chrono.ISOChronology;

import com.feed.protocol.AbstractHttpProtocolHandler;


public class HttpPostProtocolHandlerImpl extends AbstractHttpProtocolHandler  {
	 static Logger logger = Logger.getLogger(HttpPostProtocolHandlerImpl.class);

	@Override
	public String getContentText() {
		URI feedRequestURL = constructRequestURL();
		if (logger.isDebugEnabled()){
			logger.debug("Feed URL To fetch"+feedRequestURL.toString());
		}
		HttpPost httpPost = new HttpPost(feedRequestURL);
		String feedResponse= "";
        try {
        	BasicHttpContext context = new BasicHttpContext();
            // execute the method
            HttpResponse response = getHttpClient().execute(httpPost, context);
            if (logger.isDebugEnabled()){
            	logger.debug("Feed URL Response Code"+response.getStatusLine().getStatusCode());
            }
            // get the response body as an array of bytes
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                feedResponse= EntityUtils.toString(entity);
                if (logger.isDebugEnabled()){
                	logger.debug("Feed Response - "+feedResponse);
                }
            }
            
        }catch (ClientProtocolException e) {
        	httpPost.abort();
            logger.error("Feed Request Failed For URL - "+feedRequestURL ,e);
        } catch (IOException e) {
            httpPost.abort();
    		logger.error("Feed Request Failed For URL - "+feedRequestURL ,e);
        }
        return feedResponse;
	}
	
	public DateTime getLastModified() {
        DateTime lastModified = null;
        URI feedRequestURL = constructRequestURL();
		if (logger.isDebugEnabled()){
			logger.debug("Feed URL To fetch"+feedRequestURL.toString());
		}
		HttpPost httpPost = new HttpPost(feedRequestURL);
		try {
        	BasicHttpContext context = new BasicHttpContext();
            // execute the method
            HttpResponse response = getHttpClient().execute(httpPost, context);
            if (logger.isDebugEnabled()){
            	logger.debug("Feed URL Response Code"+response.getStatusLine().getStatusCode());
            }
            // get the response body as an array of bytes
            Header[] allHeaders = response.getHeaders("Date");
            for (Header header : allHeaders) {
				if (header.getName().equalsIgnoreCase("Date")){
					String timestampStr = header.getValue(); 
            		if (timestampStr != null) {
                        try {
                            DateFormat format = new SimpleDateFormat(RFC822_FORMAT, Locale.US);
                            lastModified = new DateTime(format.parse(timestampStr), ISOChronology.getInstance());
                        } catch (ParseException e) {
                            logger.warn(String.format("Could not parse Last-Modified date of [%s] from URL [%s]", timestampStr, feedRequestURL), e);
                        }
                    }
            	}
				
			}
            
        } catch (ClientProtocolException e) {
        	httpPost.abort();
            logger.error("Feed Request Failed For URL - "+feedRequestURL ,e);
        } catch (IOException e) {
        	httpPost.abort();
    		logger.error("Feed Request Failed For URL - "+feedRequestURL ,e);
        }
        return lastModified;
    }
}
